//
//  RYProductViewController.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2020/12/31.
//  Copyright © 2020 叁拾叁. All rights reserved.
//

import UIKit
import MJRefresh
import RxSwift
import RxDataSources
import Then
import SDCycleScrollView

class RYProductViewController: SYBaseTableViewController {
    
    fileprivate var vm: VGTableViewPageViewModel<RYProductListModel>!
    
    
    
    /*
     "farmId": 0,农场id
     
     "dictionaryId": 0,类型id
     
     "provinceId": 0,省id
     "cityId": 0,市id
     "districtId": 0,区县id
     "streetId": 0乡镇/街道ID
     
     "highPrice": "",价格区间 高价格
     "lowPrice": "",
     */
    var params:[String : String] = [:]
    
    var tagView: RYChoiceView!
    
    var choiceIndex: Int!
    
    var ryChoice = RYProductChoice()
    
    var choiceDatas: [[String: String]] = [[String: String]]()
    
    var choiceSecDatas: [[String: String]] = [[String: String]]()
    
    var choiceThirDatas: [[String: String]] = [[String: String]]()
    
    var erjiContent: UIView = UIView(frame: CGRect(x: 0, y: NAV_HEIGHT + 44.0.autoWidth(), width: SCREEN_WIDTH/3, height: 0.01))
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = false
    }
    
    init(farmId: String) {
        super.init(nibName: nil, bundle: nil)
        self.params["farmId"] = farmId
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setTableView()
        setNoDataView()
        setTagView()
        setupViewModel()
        
        self.title = "认养农业"
        erjiContent.backgroundColor = .red
        self.view.addSubview(erjiContent)
    }
    
    func getChoiceData(pid : Int, sec: Bool = false) {
        
        requestVM.baseRequest(disposeBag: dispose, type: .nongchangChoice(pid: pid), modelClass: SGBaseNoPageListModel<RYProductChoiceModel>.self) {[weak self] (res) in
            if let `self` = self {
                let models:[RYProductChoiceModel] = res.data ?? []
                
                if sec {
                    self.choiceSecDatas.removeAll()
                    self.ryChoice.sec.selectRow = nil
                    
                    for (_, value) in models.enumerated() {
                        self.choiceSecDatas.append(["name": value.dictionaryName ?? "", "id": value.id ?? "", "dictionaryName": value.dictionaryName ?? ""])
                    }
                    if self.choiceSecDatas.count != 0 {
                        self.ryChoice.sec.datas = self.choiceSecDatas
                    } else {
                        self.ryChoice.sec.datas = []
                        self.ryChoice.isHidden = true
                    }
                    
                } else {
                    
                    self.choiceDatas.removeAll()
                    self.ryChoice.fir.selectRow = nil
                    
                    for (_, value) in models.enumerated() {
                        self.choiceDatas.append(["name": value.dictionaryName ?? "", "id": value.id ?? "", "dictionaryName": value.dictionaryName ?? ""])
                    }
                    self.ryChoice.fir.datas = self.choiceDatas
                }
                
            }
            
        } Error: {
            
        }
    }
    
    func getAreaChoiceData(pid : Int = 0, index: Int = 0) {
        
        requestVM.baseRequest(disposeBag: dispose, type: .diqu(pid: pid), modelClass: SGBaseNoPageListModel<RYAreaModel>.self) {[weak self] (res) in
            if let `self` = self {
                let models:[RYAreaModel] = res.data ?? []
                if index == 2 {
                    
                    self.choiceThirDatas.removeAll()
                    self.ryChoice.thir.selectRow = nil
                    
                    for (_, value) in models.enumerated() {
                        self.choiceThirDatas.append(["name": value.name ?? "", "id": value.id ?? ""])
                    }
                    if self.choiceThirDatas.count != 0 {
                        self.ryChoice.thir.datas = self.choiceThirDatas
                    } else {
                        self.ryChoice.thir.datas = []
                        self.ryChoice.isHidden = true
                    }
                } else if index == 1 {
                    
                    self.choiceSecDatas.removeAll()
                    self.ryChoice.sec.selectRow = nil
                    
                    for (_, value) in models.enumerated() {
                        self.choiceSecDatas.append(["name": value.name ?? "", "id": value.id ?? ""])
                    }
                    if self.choiceSecDatas.count != 0 {
                        self.ryChoice.sec.datas = self.choiceSecDatas
                    } else {
                        self.ryChoice.sec.datas = []
                        self.ryChoice.isHidden = true
                    }
                    
                } else {
                    
                    self.choiceDatas.removeAll()
                    self.ryChoice.fir.selectRow = nil
                    
                    for (_, value) in models.enumerated() {
                        self.choiceDatas.append(["name": value.name ?? "", "id": value.id ?? ""])
                    }
                    self.ryChoice.fir.datas = self.choiceDatas
                }
                
            }
            
        } Error: {
            
        }
    }
    
    fileprivate func setupViewModel() {
        vm = VGTableViewPageViewModel<RYProductListModel>()
        vm.tableView = tableView
        vm.emptyViewParams = ("", "", 40.0, 30.0)
        tableView.vg_pageProtocol = vm
        vm.getList(type: .nongchangProductList(page: 1, size:10, dic: params), dispose: dispose)
        vm.getDataClosure = {[weak self] page in
            if let `self` = self {
                self.vm.getList(type: .nongchangProductList(page: self.vm.vg_pageNo, size:self.vm.size, dic: self.params), dispose: self.dispose)
            }
        }
        vm.loadDataClosure = {[weak self] success in
            if let `self` = self {
                if success {
                    self.loadDataSuccessed()
                }
            }
        }
    }
    
    func loadDataSuccessed() {
        DispatchQueue.main.async {
            
            self.setDataSource()
        }
    }
    
    func setTagView() {
        ryChoice = RYProductChoice(frame: CGRect(x: 0, y: NAV_HEIGHT + 44.autoWidth(), width: SCREEN_WIDTH, height: SCREEN_HEIGHT - NAV_HEIGHT - 44.autoWidth()))
        ryChoice.fir.clickedClosure = {[weak self] index in
            if let `self` = self {
                let id = self.choiceDatas[index]["id"] ?? "0"
                switch self.choiceIndex {
                case 0:
                    self.getChoiceData(pid: Int(id) ?? 0, sec: true)
                    self.params["dictionaryId"] = id
                    self.vm.getList(type: .nongchangProductList(page: 1, size:10, dic: self.params), dispose: self.dispose)
                case 1:
                    self.getAreaChoiceData(pid: Int(id) ?? 0, index: 1)
                    self.params["provinceId"] = id
                    self.vm.getList(type: .nongchangProductList(page: 1, size:10, dic: self.params), dispose: self.dispose)
                case 2:
                    self.getChoiceData(pid: Int(id) ?? 0, sec: true)
                    if let id = self.choiceDatas[index]["dictionaryName"] {
                        let price = id.components(separatedBy: "~")
                        self.params["highPrice"] = price.last
                        self.params["lowPrice"] = price.first
                        self.vm.getList(type: .nongchangProductList(page: 1, size:10, dic: self.params), dispose: self.dispose)
                    }
                default:
                    break
                }
            }
        }
        ryChoice.sec.clickedClosure = {[weak self] index in
            if let `self` = self {
                let id = self.choiceSecDatas[index]["id"] ?? "0"
                
                switch self.choiceIndex {
                case 0:
                    self.ryChoice.isHidden = true
                    self.params["dictionaryId"] = id
                    self.vm.getList(type: .nongchangProductList(page: 1, size:10, dic: self.params), dispose: self.dispose)
                case 1:
                    self.getAreaChoiceData(pid: Int(id) ?? 0, index: 2)
                    self.params["cityId"] = id
                    self.vm.getList(type: .nongchangProductList(page: 1, size:10, dic: self.params), dispose: self.dispose)
                case 2:
                    self.ryChoice.isHidden = true
                    self.params["dictionaryId"] = id
                    self.vm.getList(type: .nongchangProductList(page: 1, size:10, dic: self.params), dispose: self.dispose)
                default:
                    break
                }
            }
        }
        
        ryChoice.thir.clickedClosure = {[weak self] index in
            if let `self` = self {
                let id = self.choiceSecDatas[index]["id"] ?? "0"
                switch self.choiceIndex {
                case 0:
                    self.ryChoice.isHidden = true
                case 1:
                    self.ryChoice.isHidden = true
                    self.params["districtId"] = id
                    self.vm.getList(type: .nongchangProductList(page: 1, size:10, dic: self.params), dispose: self.dispose)
                case 2:
                    self.ryChoice.isHidden = true
                default:
                    break
                }
            }
        }
        
        tagView = RYChoiceView(frame: CGRect.init(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: 44.0.autoWidth()), titles: ["类型", "所在地区", "价格"])
        tagView.clickChoiceClosure = {[weak self] index in
            if let `self` = self {
                self.choiceSecDatas.removeAll()
                self.ryChoice.sec.selectRow = nil
                self.choiceDatas.removeAll()
                self.ryChoice.fir.selectRow = nil
                self.choiceThirDatas.removeAll()
                self.ryChoice.thir.selectRow = nil
                self.ryChoice.fir.datas = []
                self.ryChoice.sec.datas = []
                self.ryChoice.thir.datas = []
                self.choiceIndex = index
                switch index {
                case 0:
                    self.ryChoice.isHidden = false
                    self.getChoiceData(pid: 264)
                case 1:
                    self.ryChoice.isHidden = false
                    self.getAreaChoiceData()
                    
                case 2:
                    self.ryChoice.isHidden = false
                    self.getChoiceData(pid: 284)
                default:
                    break
                }
            }
        }
        view.addSubview(tagView)
        view.addSubview(ryChoice)
    }
    
    func setTableView() {
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect(x: 0, y: NAV_HEIGHT+44.0.autoWidth(), width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT-BOTTOM_SAFE_HEIGHT-44.0.autoWidth()), style:.plain)
        self.tableView.separatorStyle = .none
        self.tableView.backgroundColor = UIColor(hex: 0xF2F2F2)
        self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        self.view.addSubview(self.tableView!)
        
        tableView.rx.itemSelected
            .subscribe(onNext:{ [weak self] indexPath in
                if let `self` = self {
                    let id = self.vm.dataSource[indexPath.row].id ?? "0"
                    let vc = RYYuViewController(id: Int(id) ?? 0)
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            })
            .disposed(by:dispose)
    }
    
    func setNoDataView() {
        noDataView = SYNoDataView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT))
        noDataView.isHidden = true
        tableView.addSubview(noDataView)
    }
    
    func setDataSource() {
        //初始化数据
        let sections = Observable.just([
            ProductListSection(header: "", items: self.vm.dataSource)
        ])
        
        //创建数据源
        let dataSource = RxTableViewSectionedAnimatedDataSource<ProductListSection>(
            //设置单元格
            configureCell: { ds, tv, ip, item in
                
                let cell: RYProductCell = tv.dequeueReusableCell(withIdentifier: "Cell")
                    as? RYProductCell ?? RYProductCell(style: .default, reuseIdentifier: "Cell")
                cell.configureView(item)
                cell.selectionStyle = .none
                return cell
                
            },
            //设置分区头标题
            titleForHeaderInSection: { ds, index in
                return ds.sectionModels[index].header
            })
        tableView.dataSource = nil
        //绑定单元格数据
        sections
            .bind(to: tableView.rx.items(dataSource: dataSource))
            .disposed(by: dispose)
        
    }
    
    
}



//自定义Section
struct ProductListSection {
    var header: String
    var items: [Item]
}

extension ProductListSection : AnimatableSectionModelType {
    typealias Item = RYProductListModel
    
    var identity: String {
        return header
    }
    
    init(original: ProductListSection, items: [Item]) {
        self = original
        self.items = items
    }
}

extension RYProductListModel: IdentifiableType {
    var identity: String {
        return id!
    }
    
    typealias Identity = String
}
